import { useMemberStore } from '@/store'

const baseURL = import.meta.env.VITE_SERVER_BASEURL

const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }

    // 2. 请求超时
    options.timeout = 25000
    // 3. 添加小程序请求头标识
    options.header = {
      ...options.header,
      'source-client': 'miniapp', // 请求头添加参数
    }

    const memberStore = useMemberStore()
    const profile = memberStore.getProfile() || {}

    const token = profile.saTokenInfo ? profile.saTokenInfo.tokenValue : ''

    // const token = fakeToken
    if (token) {
      options.header.token = token
    }
    options.header['Device-Id'] = memberStore.getDeviceId()
  },
}
// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)

/**
 * 请求函数
 * @param UniApp.RequestOptions
 * @returns Promise
 * 1.返回 Promise 对象
 * 2.请求成功
 *      2.1提取核心数据
 *      2.2添加类型，支持范型
 * 3.请求失败
 *      3.1 网络错误 -> 提示用户换网络
 *      3.2 401错误 ->清理用户信息，跳转到登录页
 *      3.3 其他错误 -> 根据后端错误信息轻提示
 */

export interface Data<T> {
  code: number
  msg: string
  data: T
}
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.showLoading()

    uni.request({
      ...options,
      // 2.请求成功
      success(res) {
        uni.hideLoading()

        const memberStore = useMemberStore()
        const profile = memberStore.getProfile() || {}
        if (res.header['Update-Token']) {
          profile.token = res.header['Update-Token']
          memberStore.setProfile(profile)
        }

        if (res.header['Device-Id']) {
          memberStore.setDeviceId(res.header['Device-Id'])
        }

        if (res.statusCode === 200) {
          if ((res.data as Data<T>).code === 200) {
            resolve(res.data as Data<T>)
          } else if ((res.data as Data<T>).code === 10001) {
            uni.showToast({
              icon: 'none',
              title: (res.data as Data<T>).msg,
            })
            reject(res)
            memberStore.clearProfile()
            uni.reLaunch({
              url: '/pages/login/login',
            })
          } else {
            console.log('不是200,10001请求失败', res)

            uni.showToast({
              icon: 'none',
              title: (res.data as Data<T>).msg,
              duration: 2000,
            })
            reject(res)
          }
        } else if (res.statusCode === 401) {
          uni.showToast({
            icon: 'none',
            title: '登录状态过期，请重新登录',
            duration: 2000,
          })
          uni.reLaunch({
            url: '/pages/login/login',
          })
          memberStore.clearProfile()
          reject(res)
        } else if (res.statusCode === 1001) {
          memberStore.clearProfile()
          uni.showToast({
            icon: 'none',
            title: '请登录后再进行此操作',
          })

          uni.reLaunch({
            url: '/pages/login/login',
          })
          reject(res)
        } else {
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '请求错误',
          })
          reject(res)
        }
      },
      fail(err) {
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        })
        reject(err)
      },
    })
  })
}
